/*
 * @Descripttion: null
 * @Author: lcx
 * @version: v01
 * @Date: 2023-10-22 14:28:16
 * @LastEditors: lcx
 * @LastEditTime: 2023-10-22 16:08:45
 */

import java.util.ArrayList;
import java.util.List;

interface Subject {
    public void attach(Observer observer);
    public void detach(Observer observer);
    public void notify(Observer observer,String state);
    public void setState(String state);
    public String getState();
}

interface Observer {
    public void update(String state);

    public String getObserverState();
}

class ConcreteObserver implements Observer {
    private String observerState;
    private String name;
    private Subject subject;
    ConcreteObserver(String name,Subject subject) {
        this.name = name;
        this.subject = subject;
        subject.attach(this);
    }

    @Override
    public void update(String state) {
        observerState = state;
        System.out.println(name + " Subject recv notify state : " + state);
    }

    public String getObserverState() {
        System.out.println("name : "+ name + " now state: " + observerState);
        return observerState;
    }

}

class ConcreteSubject implements Subject {

    private String subjectState = "init";
    List<Observer> list = new ArrayList<Observer>();


    public void attach(Observer observer) {
        list.add(observer);
    }

    public void detach(Observer observer) {
        list.remove(observer);
    }

    public void notify(Observer observer,String state) {
        for (Observer object : list) {
            object.update(state);
        }
    }

    public String getState() {
        System.out.println("now state: " + subjectState);
        return subjectState;
    }

    public void setState(String state) {
        subjectState = state;
        for (Observer object : list) {
            object.update(state);
        }
    }

}
class test {
    public static void main(String[] args) {

        Subject subject = new ConcreteSubject();
        Observer observer = new ConcreteObserver("lcx", subject);
        Observer observer2 = new ConcreteObserver("lcx2", subject);

        subject.notify(observer, "secState");

        subject.setState("3thState");

        observer.getObserverState();
        observer2.getObserverState();

    }


}